package com.example.perpetualcalendar.data.network;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.jetbrains.annotations.NotNull;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public abstract class BaseRetrofit<T> {

    private static final String DATE_FORMAT = "yyyy-MM-dd'T'hh:mm:ssZ";

    private T networkService;

    private void initNetworkInterface() {
        //消息拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(@NotNull String s) {
                try {
                    String text = URLDecoder.decode(s, "utf-8");
                    Log.e("访问结果-----", text);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    Log.e("访问结果-----", s);
                }
            }
        });

        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = okHttpClientHandler(new OkHttpClient.Builder())
                .addInterceptor(loggingInterceptor)
                .build();

        Gson gson = gsonHandler(new GsonBuilder().setPrettyPrinting())
                .setDateFormat(DATE_FORMAT).create();
        Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                .baseUrl(getBaseUrl());
        Retrofit retrofit = retrofitHandler(retrofitBuilder)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(client)
                .build();
        this.networkService = retrofit.create(getRestClass());
    }

    protected T getNetworkService() {
        if (this.networkService == null) {
            initNetworkInterface();
        }
        return this.networkService;
    }

    private Retrofit.Builder retrofitHandler(Retrofit.Builder builder) {
        return builder;
    }

    OkHttpClient.Builder okHttpClientHandler(OkHttpClient.Builder builder) {
        return builder;
    }

    private GsonBuilder gsonHandler(GsonBuilder builder) {
        return builder;
    }

    protected abstract String getBaseUrl();

    protected abstract Class<T> getRestClass();
}
